package cn.jingyuan.owl.utils.core.io.resource;

import cn.jingyuan.owl.utils.core.CharsetUtils;
import cn.jingyuan.owl.utils.core.io.IORuntimeException;
import cn.jingyuan.owl.utils.core.io.IoUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * 基于 {@link InputStream} 的资源获取器<br>
 * 注意：此对象中 getUrl 方法始终返回 null
 */
public class InputStreamResource implements Resource, Serializable {

    private final InputStream in;

    private final String name;

    /**
     * 构造
     *
     * @param in {@link InputStream}
     */
    public InputStreamResource(InputStream in) {
        this(in, null);
    }

    /**
     * 构造
     *
     * @param in {@link InputStream}
     * @param name 资源名称
     */
    public InputStreamResource(InputStream in, String name) {
        this.in = in;
        this.name = name;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public URL getUrl() {
        return null;
    }

    @Override
    public InputStream getStream() {
        return this.in;
    }

    @Override
    public BufferedReader getReader(Charset charset) {
        return IoUtils.getReader(this.in, charset);
    }

    @Override
    public String readString(Charset charset) throws IORuntimeException {
        BufferedReader reader = null;
        try {
            reader = getReader(charset);
            return IoUtils.read(reader);
        } finally {
            IoUtils.close(reader);
        }
    }

    @Override
    public String readUtf8String() throws IORuntimeException {
        return readString(CharsetUtils.CHARSET_UTF_8);
    }

    @Override
    public byte[] readBytes() throws IORuntimeException {
        InputStream in = null;
        try {
            in = getStream();
            return IoUtils.readBytes(in);
        } finally {
            IoUtils.close(in);
        }
    }

}
